// store.js
import { createStore } from 'vuex';

const store = createStore({
  state() {
    return {
      isAuthenticated: false,
      token: null
    };
  },
  mutations: {
    setAuthState(state, { isAuthenticated, token }) {
      state.isAuthenticated = isAuthenticated;
      state.token = token;
    }
  },
  actions: {
    setAuth({ commit }, payload) {
      commit('setAuthState', payload);
    }
  },
  // 插件来持久化和恢复状态
  plugins: [createPersistancePlugin()]
});

function createPersistancePlugin() {
  return store => {
    const savedState = localStorage.getItem('vuex');
    if (savedState) {
      store.replaceState(Object.assign({}, store.state, JSON.parse(savedState)));
    }

    store.subscribe((mutation, state) => {
      const vieuxState = state;
      localStorage.setItem('vuex', JSON.stringify(vieuxState));
    });
  };
}

export default store;